<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Session;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $noNeedRight = ['getMobile'];
    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($this->auth->isSuperAdmin() || Session::get('admin.id') === 2) {
                $total = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $list  = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with('gymnasium')
                    ->where($where)
                    ->where(['gymnasium.gymnasium_id' => session('admin.gymnasium_id')])
                    ->order($sort, $order)
                    ->count();
                $list  = $this->model
                    ->with('gymnasium')
                    ->where($where)
                    ->where(['gymnasium.gymnasium_id' => session('admin.gymnasium_id')])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));

        // 查找上级
        $parent = Db::name('user')->where(['id' => $row['parent_id']])->field('nickname,mobile,avatar')->find();
        // 查找下级
        $extension = Db::name('user')->where(['parent_id' => $row['id']])->field('nickname,mobile,avatar')->select();

        $this->view->assign(['parent' => $parent, 'extension' => $extension]);
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    public function gymnasium()
    {
        $keyValue = input('keyValue');
        if ($keyValue) {
            $list = Db::name('user')
                ->alias('user')
                ->where(['user.id' => $keyValue])
                ->field('user.id,user.mobile')
                ->paginate(null, false, ['page' => 1, 'list_rows' => 10]);
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list->toArray()['data']]);
        } else {
            $list = Db::name('user')
                ->alias('user')
                ->join('user_gymnasium gymnasium', 'gymnasium.user_id = user.id')
                ->where(['gymnasium.gymnasium_id' => Session::get('admin.gymnasium_id')])
                ->field('user.id,user.mobile')
                ->paginate(null, false, ['page' => input('pageNumber'), 'list_rows' => input('pageSize')]);
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list->toArray()['data']]);
        }

    }

    public function getMobile()
    {
        $mobile   = input('mobile');
        $keyValue = input('keyValue');
        if (!$mobile) {
            $mobile = '1';
        }
        if ($keyValue) {
            $list = Db::name('user')
                ->alias('user')
                ->where('id', "=", $keyValue)
                ->field('user.id,user.mobile,user.nickname')
                ->paginate(null, false, ['page' => 1, 'list_rows' => 10])
                ->each(function ($item) {
                    $item['mobile'] = $item['mobile'] . ' 昵称=》' . $item['nickname'];
                    return $item;
                });
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list->toArray()['data']]);
        } else {
            $list = Db::name('user')
                ->alias('user')
                ->whereLike('mobile', "$mobile%")
                ->where('mobile', "<>", '')
                ->field('user.id,user.mobile,user.nickname')
                ->paginate(null, false, ['page' => input('pageNumber'), 'list_rows' => 10])
                ->each(function ($item) {
                    $item['mobile'] = $item['mobile'] . ' 昵称=》' . $item['nickname'];
                    return $item;
                });

            $total = Db::name('user')
                ->alias('user')
                ->whereLike('mobile', "$mobile%")
                ->where('mobile', "<>", '')
                ->field('user.id')
                ->count('user.id');
            //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
            return json(['list' => $list->toArray()['data'], 'total' => $total]);
        }
    }

}
